package com.ziytek.web.citizen.handler;

import com.google.gson.Gson;
import com.ziytek.web.citizen.config.ConfigInit;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.util.DataUtils;
import com.ziytek.web.citizen.util.SpringBeanUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.List;

/**
 * @author fenghx
 * @version v1.0
 * @className MyDecoder
 * @descripton 16进制解码
 * @date 2023/4/13 11:37
 **/
@Slf4j
public class MyDecoder extends ByteToMessageDecoder {
    private static final Gson GSON = new Gson();
    private static final ConfigInit CONFIG_INIT = SpringBeanUtils.getApplicationContext().getBean(ConfigInit.class);


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        //创建字节数组,buffer.readableBytes可读字节长度
        var b = new byte[buffer.readableBytes()];
        //复制内容到字节数组b
        buffer.readBytes(b);

        if (CONFIG_INIT.isPrint()) {
            log.info("测试模式,打印数据:{}", GSON.toJson(toHexString(b)));
        }

        // 指令下发回应结果
        if (b.length == NumConstant.INT_THIRTEEN) {
            out.add(DataUtils.commandResponse(b));
            return;
        }

        // 周期数据
        if (b.length == NumConstant.INT_SIX_NINE_EIGHT) {
            out.add(DataUtils.parseRealData(b));
            return;
        }

        // 断连,设备端重新请求业务 示例: AA0003070200010007CC0D0A
        if (b.length == NumConstant.INT_TWELVE) {
            out.add(DataUtils.parseDeviceRequest(b));
            return;
        }

        //字节数组转字符串
        out.add(toHexString(b));
    }


    private String toHexString(byte[] b) {
        var buffer = new StringBuilder();
        for (byte value : b) {
            buffer.append(toHexString(value));
        }
        return buffer.toString();
    }

    private String toHexString(byte b) {
        var s = Integer.toHexString(b & 0xFF);
        return s.length() == NumberUtils.INTEGER_ONE ? "0" + s.toUpperCase() : s.toUpperCase();
    }
}
